"""
Functions to read in data from Stanford Research QCM
"""

import serial
import io
import datetime
import pandas as pd
import csv
from time import sleep
from matplotlib import pyplot as plt
from pdb import set_trace

def qcm_monitor(port=0, dt=1, fname="qcm.dat", t=1e10):
    """ 
    Open a serial connection with settings required by the Stanford
    Research QCM. Request the frequency and resistance at 1 second intervals
    and write to a text file with date and time stamps indefinetely.  
    port : port name on computer (see /dev/tty for available ports) 
            Note that the port must have write permission.
    baudrate : integer - baudrate of transfer (see manual to set or individual 
        functions to set)
    bytesize : integer - number of bits
    parity : string [E | N | O] parity check
    dt : time delta between reads
    fname : string of filename to save data
    t : float number of seconds to record data
    """
    ser = serial.Serial(port, baudrate=9600, bytesize=8, parity='N', timeout=1)
    sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))
    with open(fname, mode='a') as fObj:
        fObj.write("Date Time Frequency Resistance\r\n")
        start = datetime.datetime.now()
        t = datetime.datetime.now()
        delta = t - start
        while delta.seconds < t:
            sio.write(u"F\r")
            sleep(0.1)
            sio.flush()
            freq = ser.readline().replace("\r\n", "")
            sio.write(u"R\r")
            sleep(0.1)
            sio.flush()
            res = ser.readline().replace("\r\n", "")
            data = " ".join([str(t), str(freq), str(res), "\r\n"])
            fObj.write(data.strip())
            fObj.flush()
            sleep(dt)
            t = datetime.datetime.now()
            delta = t - start
        fObj.close()

def read_data(fname):
    """
    Read and parse the data file.
    fname : string of path name to data file
    """
    df = pd.read_csv(fname, sep=" ", header=0)
    del df['Unnamed: 4']
    df['Time'] = pd.to_datetime(df['Date'] + " " + df['Time'],
            format="%Y-%m-%d %H:%M:%S.%f")
    del df['Date']
    return df

def make_plot(fname):
    """
    Plot the contenst of a text file collected from the qcm
    function.
    fname : string of path name to data file
    return : matplotlib.AxesSubplot
    """
    df = read_data(fname)
    df['Delta'] = df['Time'] - df['Time'][0]
    df['Delta'] = [float(d)/(1.e9 * 3600) for d in df['Delta']]
    ax = df.plot(x='Delta', y='Frequency', color='blue')
    ax.set_xlabel(r"$\Delta t$ (hr)")
    ax.set_ylabel(r"$f$ (MHz)", color='blue')
    #set_trace()
    ax2 = ax.twinx()
    ax2.plot(df['Delta'], df['Resistance'], color='green')
    ax2.set_ylabel(r"$R$ (Ohm)", color='green')
    plt.draw(); plt.show()
    return 

if __name__ == "__main__":
    qcm_monitor()
